﻿using System;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.IdentityModel.Tokens.Jwt;
using System.Collections.Generic;
using MineMES.Application.DTO;
using Newtonsoft.Json;

namespace MineMES.Application.AppHelper
{
    public static class GetToken
    {
        public static string Login(SysUserDto user)
        {
            var secret = AppConfigurtaionServices.Configuration.GetSection("tokenManagement:secret").Value;
            var issuer = AppConfigurtaionServices.Configuration.GetSection("tokenManagement:issuer").Value;
            var audience = AppConfigurtaionServices.Configuration.GetSection("tokenManagement:audience").Value;
            var accessExpiration = int.Parse(AppConfigurtaionServices.Configuration.GetSection("tokenManagement:accessExpiration").Value);
            var refreshExpiration = int.Parse(AppConfigurtaionServices.Configuration.GetSection("tokenManagement:refreshExpiration").Value);
            var token = new TokenManagement();
            token.Issuer = issuer;
            token.Audience = audience;
            token.AccessExpiration = accessExpiration;
            token.Secret = secret;
            token.RefreshExpiration = refreshExpiration;
            //Audience
            var handler = new JwtSecurityTokenHandler();

            var claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.NameIdentifier, user.UserNo));
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(token.Secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //.NET Core’s JwtSecurityToken class takes on the heavy lifting and actually creates the token.
            /**
             * Claims (Payload)
                Claims 部分包含了一些跟这个 token 有关的重要信息。 JWT 标准规定了一些字段，下面节选一些字段:

                iss: The issuer of the token，token 是给谁的
                sub: The subject of the token，token 主题
                exp: Expiration Time。 token 过期时间，Unix 时间戳格式
                iat: Issued At。 token 创建时间， Unix 时间戳格式
                jti: JWT ID。针对当前 token 的唯一标识
                除了规定的字段外，可以包含其他任何 JSON 兼容的字段。
             * */
            var rutoken = new JwtSecurityToken(
                issuer: token.Issuer,
                audience: token.Audience,
                claims: claims,
                expires: DateTime.Now.AddMinutes(token.RefreshExpiration),
                signingCredentials: creds);
            return handler.WriteToken(rutoken);
            //return new JwtSecurityTokenHandler().WriteToken(rutoken);
        }
    }
}
